<template>
  <div class="about">
    <div for="">
      <div>上传图片（宽不能大于200w, 高不能大于200h）:</div>
      <div>{{error}}</div>
    </div>
    <div class="choiceBox" @click="useUpload">
      <span v-show="!imgUrl" class="icon">+</span>
      <img :src="imgUrl" alt="" style="max-height: 200px; max-width: 200px" />
    </div>
    <input
      class="fileInp"
      type="file"
      style="display: none"
      @change="uploadImg"
    />
  </div>
</template>
<script>
export default {
  //可在父组件使用@request传入函数用于接收param（param是FormData文件）
  props: {
    //请求地址
    url: {
      type: String,
      default: "",
    },
    imgUrl:{
      type: String,
      default: "",
      // 'https://mylink.oss-accelerate.aliyuncs.com/xinshan/haimian1639013786715.gif'
    }
  },
  data() {
    return {
      imgList: [],
      error:""
    };
  },
  methods: {
    useUpload() {
      //ie浏览器
      if (document.all) {
        document.getElementsByClassName("fileInp")[0].click();
      } else {
        // 其它浏览器
        let e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementsByClassName("fileInp")[0].dispatchEvent(e);
      }
    },
    uploadImg(e) {
      let that = this;
      let file = e.target.files[0];
      let reader = new FileReader();
      reader.readAsDataURL(file);
      that.error=""
      reader.onload = function (target) {
        let img = new Image();
        //此处的this指向原型对象
        img.src = this.result;
        //挂载错误
        img.onerror = function (e) {
          console.log("图片已损坏");
          return false;
        };
        //挂载成功
        img.onload = function () {
          let width = img.width;
          let height = img.height;
          // 限制大小1
          if (width > 200 || height >200) {
            console.log("图片尺寸不正确，宽不能大于200w, 高不能大于200h");
            that.error='图片尺寸不正确，宽不能大于200w, 高不能大于200h'
            return false;
          }
          //限制大小2
          // if (width / height !== 500 / 500) {
          //   console.log("图片尺寸大小不匹配（标准宽高比为：500w/500h)")
          //   return false;
          // }
          console.log("可以存储", file);
          //发送请求存储图片
          let param = new FormData();
          //加入formdata
          param.append("file", file);
          //传入动态函数可用于返回请求数据结果
          //也可参照下面的写法封装请求
          that.$emit("request", param);
          //请求可在api文件单独分装api.upLoadFile=function(){"对数据操作"然后return axios.post()}
          //设置请求头
          // let config = {
          //   headers: {
          //     "Content-Type": "multipart/form-data",
          //     Authorization: localStorage.getItem("token"),
          //   },
          // };
          // //发送请求
          // axios.post(that.url, param, config).then((res) => {
            //res中的返回地址赋值给imgUrl
          //   console.log(res,'请传入函数用于接收返回值');
          // });
        };
      };
    },
  },
};
</script>
<style lang="scss" scoped>
// <style lang="less" scoped>
* {
  box-sizing: border-box;
}
.about {
  display: flex;
  justify-content: flex-start;
  .imgBox {
    width: 200px;
    height: 200px;
    border: 1px solid #f1f1f1;
  }
  .choiceBox {
    margin-left: 20px;
    width: 200px;
    height: 200px;
    border: 1px solid #f1f1f1;
    display: flex;
    justify-content: center;
    align-items: center;
    .icon {
      font-size: 150px;
      display: block;
      color: #f1f1f1;
    }
  }
}
</style>

